package com.cy.pj.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
public class AjaxController {
    //private List<String> names = new ArrayList<>();
    private List<Map<String, Object>> data = new ArrayList<>();

    public AjaxController() {
        Map<String, Object> map = new HashMap<>();
        map.put("id", "100");
        map.put("name", "华为");
        map.put("remark", "Good");
        data.add(map);
    }

    @PutMapping("/doAjaxPut")
    @ResponseBody
    public String doAjaxPut(@RequestParam Map<String, Object> map) {
        String id = (String) map.get("id");
        Iterator<Map<String, Object>> iterator = data.iterator();
        Map<String, Object> obj = null;// 先找到，再更新数据
        while(iterator.hasNext()) {
            obj = iterator.next();
            if(obj.get("id").equals(id)) {
                break;
            }
        }
        obj.put("name", map.get("name"));
        obj.put("remark", map.get("remark"));
        return "update ok";
    }

    @DeleteMapping("/doAjaxDelete/{id}")
    @ResponseBody
    public String doAjaxDelete(@PathVariable Integer id) {
        Iterator<Map<String, Object>> iterator = data.iterator();
        while(iterator.hasNext()) {
            Map<String, Object> map = iterator.next();
            if(map.get("id").equals(String.valueOf(id))) {
                iterator.remove();// 用迭代器删除
            }
        }
        return "delete ok";
    }

    @PostMapping("/doAjaxPost")
    //@RequestMapping(value = "/doAjaxPost",method = RequestMethod.POST)
    @ResponseBody
    public String doAjaxPost(@RequestParam Map<String, Object> map) {
        data.add(map);
        return "save ok";
    }

    @CrossOrigin // 此注解描述的方法允许跨域访问
    @GetMapping("/doAjaxGet")
    //@RequestMapping(value = "/doAjaxGet", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> doAjaxGet() {
        return data;
    }

    @RequestMapping("/doAjaxStart")
    @ResponseBody
    public String doAjaxStart() /*throws InterruptedException*/ {
        //Thread.sleep(5000);
        System.out.println("AjaxController.doAjax");
        return "Ajax Get request result";
    }

    // localhost/doNotAjax
    @RequestMapping("/doNotAjax")
    public String doNotAjax() {
        return "not-ajax-01";
    }

    @RequestMapping("/doNotAjaxStart")
    public String doNotAjaxStart(Model model) {
        model.addAttribute("result", "the not ajax");
        return "not-ajax-01";
    }

    // http://localhost/doGetAjax
    @RequestMapping("/doGetAjax")
    public String doGetAjax() {
        return "ajax-demo";
    }

    @RequestMapping("/doSave")
    @ResponseBody
    public String doSave(String name) {
        //if(!names.contains(name)) {
        //    names.add(name);
        //}
        return "save success";
    }
}
